const md5 = require('md5')

export class SignParams {
  secret = 'witkey_console'
  appId = 100002

  constructor(params) {
    this.params = params
  }

  getParams() {
    this.params.nonce = Math.random()
    this.params.timestamp = Date.now() / 1000
    this.params.app_id = this.appId
    let keys = []
    for (let key in this.params) {
      keys.push(key)
    }

    let param = []
    for (let key in this.params) {
      param[key] = this.params[key]
    }

    this.params.signature = this.sign(keys, param)

    return this.params
  }

  sign(key, val) {
    let str = ''
    const s = key.sort()

    for (let i in s) {
      if (val[s[i]] !== '') {
        str += s[i] + '=' + val[s[i]] + '&'
      }
    }
    str += ('secret=' + this.secret)
    return md5(str)
  }
}
